<?php
/**
 * 非企微客户
 * User: 万奇
 * Date: 2021/11/26 19:03
 */

namespace app\admin\model;


use think\facade\Db;

class EnterCustomer extends BasicModel
{
    public function __construct(array $data = [])
    {
        parent::__construct($data);
    }

    /**
     * 修改客户详情
     * User: 万奇
     * Date: 2021/7/13 16:56
     * @param $param
     * @param $add_user - 操作人 user_id
     * @param $user_type 1-系统人员 2-企业成员
     * @throws \think\db\exception\DbException
     */
    public function edit_enter_customer_info($param, $add_user, $user_type = 1){
        if (isset($param['follow_remark_mobiles'])){
            $reg_phone                   = reg_phone($param['follow_remark_mobiles']);
            if (!$reg_phone){
                response(500, '手机号码格式不正确');
            }
        }

        // 客户互动轨迹
        $param['not_qw']                =  1;
        (new \app\admin\model\WxkCustomer())->edit_customer_action_log($param, $add_user, $user_type);

        $this->where(['id' => $param['external_user_id']])->update($param);
        Db::name('wxk_customer_portrait')->where(['external_user_id' => $param['external_user_id'], 'corp_id' => $param['corp_id']])->update($param);
    }

    /**
     * 非企微客户详情
     * User: 万奇
     * Date: 2021/12/31 18:33
     * @param $param
     * @return array|mixed
     * @throws \think\db\exception\DbException
     */
    public function enter_customer_info($param){
        $data               = ['export' => 1, 'id' => $param['id']];

        if (!empty($param['is_pool'])){
            $data['is_pool'] = $param['is_pool'];
        }

        $result             = $this->get_enter_customer_list($data);

        !isset($result['data'][0]) ? response(200, '暂无数据') : $result = $result['data'][0];

        return $result;
    }

    /**
     * 非企微客户退回公海
     * User: 万奇
     * Date: 2021/12/31 18:32
     * @param $param
     * @param $user_info
     * @param int $user_type
     */
    public function back_pool_enter_customer($param, $user_info, $user_type = 1){
        $this->where(['id' => $param['id']])->update(['is_pool' => 1]);

        // 添加客户轨迹
        $user_name      = get_operator_name($user_info, $user_type);
        $user_name      = Db::name('sys_user')->where(['id' => $user_info['user_id']])->value('username');
        WxkCustomerTrack::add_customer_track($param['id'], "$user_name 将客户退回公海", 2);
    }

    /**
     * 非企微客户转交判断是否已拥有客户
     * User: 万奇
     * Date: 2021/12/24 18:38
     * @param $param
     * @return bool
     */
    public function enter_customer_shift_judge($param){
        $result     = $this->where(['id' => $param['id'], 'follow_userid' => $param['replace_staff']])->count();

        return $result ? true : false;
    }

    /**
     * 转交非企微客户
     * User: 万奇
     * Date: 2021/7/13 14:29
     * @param $param
     * @param $user_info
     * @param $user_type - 1为PC端
     */
    public function shift_enter_customer($param, $user_info, $user_type = 1){
        $old_staff      = $this->where(['id' => $param['id']])->value('follow_userid');
        $where          = [['user_id', 'in', [$old_staff, $param['staff_id']]]];
        $staff          = Db::name('wxk_staff')->where($where)->column('name', 'user_id');
        $this->where(['id' => $param['id']])->update(['follow_userid' => $param['staff_id'], 'follow_time' => format_time(time())]);

        // 添加客户轨迹
        $user_name      = get_operator_name($user_info, $user_type);
        $txt            = "$user_name 转交客户给成员 : {$staff[$param['staff_id']]}，原成员：{$staff[$old_staff]}";
        WxkCustomerTrack::add_customer_track($param['id'], $txt, 2);

        // 发送应用消息
        $name           = $this->where(['id' => $param['id']])->value('name');
        $txt            = $user_type == 1 ? '管理员' : "@$user_name" . " 将非企微客户【{$name}】转交给你，请注意及时跟进";
        WxkApp::app_msg_send($param['staff_id'], $txt);
    }

    /**
     * 客户打标签/移除标签
     * User: 万奇
     * Date: 2021/12/17 18:41
     * @param $param
     * @param $user_info
     * @param $user_type - 1为PC端
     */
    public function enter_customer_tagging($param, $user_info, $user_type = 1){
        $customer           = $this->where([['id', 'in', implode(',', $param['id'])]])->column('id as external_user_id,tag_ids', 'id');
        $tag_name           = Db::name('wxk_customer_tag')->column('name', 'id');
        $user_name          = get_operator_name($user_info, $user_type);

        if ($param['type'] == 1){
            foreach ($customer as $k => $v){
                $update['tag_ids']     = implode(',', $v['tag_ids'] ? array_unique(array_merge(explode(',', $v['tag_ids']), $param['tag_ids'])) : $param['tag_ids']);
                $this->where(['id' => $k])->update($update);

                // 添加客户轨迹
                $tag_txt            = [];
                foreach ($param['tag_ids'] as $t_k => $t_v){
                    $tag_txt[$t_k]        = $tag_name[$t_v];
                }

                $txt                = "$user_name 对客户添加标签 : " . implode('、', $tag_txt);
                WxkCustomerTrack::add_customer_track( $v['external_user_id'], $txt, 2);
            }
        } else{
            foreach ($customer as $k => $v){
                $update['tag_ids']     = implode(',', array_diff(explode(',', $v['tag_ids']), $param['tag_ids']));
                $this->where(['id' => $k])->update($update);

                // 添加客户轨迹
                $tag_txt            = [];
                foreach ($param['tag_ids'] as $t_k => $t_v){
                    $tag_txt[$t_k]        = $tag_name[$t_v];
                }

                $txt                = "$user_name 对客户移除标签 : " . implode('、', $tag_txt);
                WxkCustomerTrack::add_customer_track($v['external_user_id'], $txt, 2);
            }
        }
    }

    /**
     * 导入非企微客户
     * User: 万奇
     * Date: 2021/7/13 10:44
     * @param $param
     * @param $user_info
     * @param $is_pool -是否是客户池
     * @return array
     */
    public function enter_customer_import($param, $user_info, $is_pool = false){
        try {
            $file = request()->file('file');

            if (!$file){
                response(500, '请选择文件');
            }

            // 验证文件规则
            validate(['file' => 'filesize:10240000|fileExt:xlsx'])->check(['file' => $file]);

            // 上传文件
            $file_name = uuid() . '.xlsx';
            $file->move( './uploads', $file_name);

            // 载入excel文件
            $reader     = \PHPExcel_IOFactory::createReader('Excel2007');
            $excel      = $reader->load('./uploads/' . $file_name);
            $list       = $excel->getSheet()->toArray();
            array_splice($list, 0, 2);

            // 删除上传的文件
            unlink('./uploads/' . $file_name);

            // 组装数据
            $intention  = ['暂无意向' => 1, '观望中' => 2, '有意向' => 3];
            $staff_list = Db::name('wxk_staff')->column('user_id', 'name');
            $field      = array_grouping(Db::name('enter_customer_field')->column('id,pid,name'), 'pid');
            $follow     = $field[array_column($field[0], 'id', 'name')['跟进状态']];
            $add_way    = array_column($field[array_column($field[0], 'id', 'name')['客户来源']], 'id', 'name');
            $industry   = Db::name('sys_category')->where(['pid' => 1])->column('id', 'name');
            $mobile     = Db::name('enter_customer')->whereNotNull('follow_remark_mobiles')->column('id', 'follow_remark_mobiles');
            $user_name  = get_operator_name($user_info, true);

            $insert     = $por_insert = $track_insert = $error = [];
            foreach ($list as $v){
                if (!$is_pool && isset($v[8]) && isset($staff_list[$v[8]])){
                    $error['name'][]     = $v[8];
                    continue;
                }
                if ($v[1]){
                    if (!reg_phone($v[1])){
                        $error['rule'][]     = $v[1];
                        continue;
                    }
                    if (isset($mobile[$v[1]])){
                        $error['mobile'][]     = $v[1];
                        continue;
                    }
                    $insert_mobile   = array_column($insert, 'follow_remark_mobiles', 'follow_remark_mobiles');
                    if (isset($insert_mobile[$v[1]])){
                        $error['mobile2'][]     = $v[1];
                        continue;
                    }
                }

                $external_id                = uuid();
                $insert[]                   = [
                    'id'                    => $external_id,
                    'name'                  => $v[0],
                    'follow_userid'         => $is_pool ? $staff_list[$v[8]] : '',
                    'follow_remark_mobiles' => $v[1],
                    'follow_add_way'        => isset($add_way[$v[4]]) ? $add_way[$v[4]] : '',
                    'follow_status'         => $follow[0]['id'],
                    'follow_time'           => format_time(time()),
                    'is_pool'               => $is_pool ? 0 : 1
                ];

                $por_insert[]           = [
                    'id'                => uuid(),
                    'external_user_id'  => $external_id,
                    'name'              => $v[0],
                    'intention'         => isset($intention[$v[3]]) ? $intention[$v[3]] : '',
                    'industry'          => isset($industry[$v[5]]) ? $industry[$v[5]] : '',
                    'area'              => $v[6],
                    'address'           => $v[7],
                    'wechat'            => $v[2],
                ];

                // 客户轨迹
                $txt                    = "$user_name 批量添加了该客户";
                $track_insert[]         = ['id' => uuid(), 'external_user_id' => $external_id, 'content' => $txt, 'type' => 2];
            }

            Db::name('enter_customer')->insertAll($insert);
            Db::name('wxk_customer_portrait')->insertAll($por_insert);
            Db::name('wxk_customer_track')->insertAll($track_insert);

            return ['success' => count($insert), 'error' => $error ?: (object)[]];
        } catch (\Exception $e) {
            response(500, $e->getMessage());
        }
    }

    /**
     * 非企微客户列表
     * User: 万奇
     * Date: 2021/7/9 16:05
     * @param $param
     * @return array
     * @throws \think\db\exception\DbException
     */
    public function get_enter_customer_list($param){
        $where          = [['a.is_pool', '=', isset($param['is_pool']) ? $param['is_pool'] : 0]];

        if (is_exists($param['clue_name'])){
            $where[]    = ['a.clue_name', 'like', "%{$param['clue_name']}%"];
        }

        if (is_exists($param['keyword'])){
            $where[]    = ['a.name|a.follow_remark_mobiles', 'like', "%{$param['keyword']}%"];
        }

        if (is_exists($param['follow_add_way'])){
            $where[]    = ['a.follow_add_way', '=', $param['follow_add_way']];
        }

        if (is_exists($param['follow_userid'])){
            $where[]    = ['a.follow_userid', '=', $param['follow_userid']];
        }

        $tag_ids        = '';
        if (is_exists($param['tag_ids'])){
            $tag_ids    = "a.tag_ids regexp replace('{$param['tag_ids']}',',','|')";
        }

        if (is_exists($param['id'])){
            $where[]    = ['a.id', '=', $param['id']];
        }

        $field          = 'a.id,a.name,a.tag_ids,a.follow_userid,a.follow_add_way,a.follow_remark,a.follow_remark_mobiles,
                        a.follow_status,a.clue_name,a.is_change,a.create_at,b.email,b.qq,b.hobby,b.income,b.company,b.intention,
                        b.industry,b.wechat,b.area,b.address,b.photo,b.photo_txt';

        // 客户导出
        if (isset($param['export'])){
            $list['data']   = $this->alias('a')->field($field)
                ->join('wxk_customer_portrait b', 'a.id=b.external_user_id', 'left')
                ->where($where)->where($tag_ids)->order(['a.create_at' => 'desc'])->select()->toArray();
        } else{
            $list   = $this->alias('a')->where($where)->where($tag_ids)->order(['a.create_at' => 'desc'])->paginate($param['limit'])->toArray();
        }

        $follow     = (new EnterCustomerField())->get_customer_field('跟进状态');
        $add_way    = (new EnterCustomerField())->get_customer_field('客户来源');
        $tag_name   = Db::name('wxk_customer_tag')->column('name', 'id');
        $industry   = Db::name('sys_category')->where(['pid' => 1])->column('name', 'id');
        $section    = Db::name('wxk_department')->column('name', 'code');
        $s_where    = [['user_id', 'in', implode(',', array_filter(array_column($list['data'], 'follow_userid')))]];
        $staff_name = Db::name('wxk_staff')->where($s_where)->column('name,department_id', 'user_id');

        foreach ($list['data'] as &$v){
            $v['follow_add_way']        = isset($add_way[$v['follow_add_way']]) ? $add_way[$v['follow_add_way']] : '';
            $v['follow_status']         = $follow[$v['follow_status']];
            $v['tag_ids']               = get_name_attr($tag_name, $v['tag_ids']);

            // 详情
            if (!empty($param['id']) && $v['follow_userid']){
                $v['section_name']      = implode('/', get_name_attr($section, $staff_name[$v['follow_userid']]['department_id']));
            }

            // 导出
            if (isset($param['export'])){
                $v['intention']         = $v['intention'] ? [1 => '暂无意向', 2 => '观望中', 3 => '有意向'][$v['intention']] : '';
                $v['industry']          = $v['industry'] ? $industry[$v['industry']] : '';
            } else{
                $v['staff_name']            = $v['follow_userid'] ? $staff_name[$v['follow_userid']]['name'] : '';
                $v['add_user']              = $v['is_pool'] == 2 ? get_operator_name(['corp_id' => $param['corp_id'], 'user_id' => $v['add_user']], $v['add_user_type']) : '';
            }
        }

        return $list;
    }

    /**
     * 添加非企微客户
     * User: 万奇
     * Date: 2021/11/26 19:03
     * @param $param
     * @param $user_info - 操作用户
     * @param $user_type - 1为管理端 2-移动端
     */
    public function add_enter_customer($param, $user_info, $user_type = 1){
        $external_user_id   = uuid();
        $follow_id          = Db::name('enter_customer_field')->where(['name' => '未跟进'])->value('id');
        $c_insert           = [
            'id'            => $external_user_id,
            'follow_status' => $follow_id,
            'follow_time'   => format_time(time()),
            'add_user'      => $user_info['user_id'],
            'add_user_type' => $user_type
        ];

        $c_insert['name']       = isset($param['name']) ? $param['name'] : '';
        $c_insert['is_pool']    = isset($param['is_pool']) ? $param['is_pool'] : 0;

        if (isset($param['clue_name'])){
            $c_insert['clue_name']              = $param['clue_name'];
        }
        if (isset($param['follow_userid'])){
            $c_insert['follow_userid']          = $param['follow_userid'];
        }
        if (isset($param['tag_ids'])){
            $c_insert['tag_ids']                = $param['tag_ids'];
        }
        if (isset($param['follow_remark'])){
            $c_insert['follow_remark']          = $param['follow_remark'];
        }
        if (isset($param['follow_add_way'])){
            $c_insert['follow_add_way']         = $param['follow_add_way'];
        }
        if (isset($param['follow_remark_mobiles'])){
            $reg_phone                          = reg_phone($param['follow_remark_mobiles']);
            if (!$reg_phone){
                response(500, '手机号码格式不正确');
            }
            $c_insert['follow_remark_mobiles']  = $param['follow_remark_mobiles'];
        }

        $this->insert($c_insert);

        // 添加客户画像
        $param['id']                            = uuid();
        $param['external_user_id']              = $external_user_id;
        Db::name('wxk_customer_portrait')->insert($param);

        // 添加客户轨迹
        $user_name          = get_operator_name($user_info, $user_type);
        $txt                = "$user_name 添加了该客户";
        WxkCustomerTrack::add_customer_track($external_user_id, $txt, 2);
    }

    /**
     * 回显新增编辑非企微客户数据
     * User: 万奇
     * Date: 2021/11/26 19:03
     * @param $param
     * @return array
     */
    public function show_edit_enter_customer($param){
        $industry       = Db::name('sys_category')->where(['pid' => 1])->column('id,name');
        $field          = array_grouping(Db::name('enter_customer_field')->column('id,pid,name'), 'pid');
        $follow         = $field[array_column($field[0], 'id', 'name')['跟进状态']];
        $add_way        = $field[array_column($field[0], 'id', 'name')['客户来源']];
        return ['follow' => $follow, 'add_way' => $add_way, 'industry' => $industry];
    }

}